<template>
  <view class="content w-100">
    <view class="search ss-flex justify-center align-center bg-white w-100">
      <view class="search-box ss-flex justify-start align-center ss-p-x-30 ss-m-r-24">
        <uni-icons type="search" size="22" color="#B2B2B2"></uni-icons>
        <input
          class="flex-sub ss-m-l-10"
          v-model="state.keyword"
          type="text"
          placeholder="搜索"
          @input="input"
          @confirm="search"
        />
      </view>
      <view class="right" @click="search" v-if="state.is_search">搜索</view>
      <view class="right" @click="cancel" v-else>取消</view>
    </view>
    <view class="location w-100 bg-white ss-p-x-28 ss-p-y-22">
      <view class="title ss-font-24">当前定位</view>
      <view class="ss-flex justify-between align-center ss-m-t-36">
        <view class="address ss-flex justify-center ss-font-32">
          <image
            src="https://xyh-static-app.oss-cn-hangzhou.aliyuncs.com/storage_2/13mansion/area-left.png"
          ></image>
          <view class="ss-m-l-10">{{ state.city.city_name }}</view>
        </view>
        <view class="reload ss-flex justify-center ss-font-24" @click="getLocation">
          <image
            src="https://xyh-static-app.oss-cn-hangzhou.aliyuncs.com/storage_2/13mansion/area-right.png"
          ></image>
          <view class="ss-m-l-10">重新定位</view>
        </view>
      </view>
    </view>

    <scroll-view
      class="scroll ss-p-x-28 ss-p-y-24 bg-white ss-m-t-16"
      :scroll-y="true"
      :scroll-into-view="state.scrollIntoView"
      :enable-back-to-top="true"
      :scroll-with-animation="true"
    >
      <!-- <view class="hot ss-m-b-40">
				<view class="title ss-m-b-32">热门城市</view>
				<view class="list ss-flex justify-start align-center flex-wrap">
					<view class="item ss-m-b-24 text-center ss-m-r-30">北京</view>
					<view class="item ss-m-b-24 text-center ss-m-r-30">北京</view>
					<view class="item ss-m-b-24 text-center ss-m-r-30">北京</view>
					<view class="item ss-m-b-24 text-center ss-m-r-30">北京</view>
					<view class="item ss-m-b-24 text-center ss-m-r-30">北京</view>
					<view class="item ss-m-b-24 text-center ss-m-r-30">北京</view>
					<view class="item ss-m-b-24 text-center ss-m-r-30">北京</view>
					<view class="item ss-m-b-24 text-center ss-m-r-30">北京</view>
				</view>
			</view> -->
      <view v-for="(item, index) in state.list" :key="index" :id="`item-${index}`">
        <view class="title ss-m-b-32" :id="index">{{ index }}</view>
        <view class="list ss-flex justify-start align-center flex-wrap">
          <view
            class="item ss-m-b-24 text-center ss-m-r-30 ss-line-1 ss-p-x-20"
            v-for="(row, page) in item"
            :key="page"
            @click="change(row)"
          >
            {{ row.name }}
          </view>
        </view>
      </view>
    </scroll-view>

    <view class="fixed-index ss-flex flex-column justify-center align-center">
      <view v-for="(item, index) in state.list" :key="index" @click="toAnchor(index)">{{
        index
      }}</view>
    </view>
  </view>
</template>

<script setup>
import city from "./data.js";
import { reactive, nextTick, getCurrentInstance } from "vue";
import { onLoad } from "@dcloudio/uni-app";
import sheep from "@/sheep";

let eventChannel = null;
// 地铁站位置常量
const DEFAULT_LOCATION = {
  latitude: 30.308041, // 默认坐标
  longitude: 120.372893,
  city_name: "杭州市",
  pid:33
};

// 修改初始状态
const state = reactive({
  scrollIntoView: "",
  list: [],
  city: {
    city_name: DEFAULT_LOCATION.city_name,
    latitude: DEFAULT_LOCATION.latitude,
    longitude: DEFAULT_LOCATION.longitude,
  },
  keyword: "",
  is_search: true,
});

onLoad(() => {
  try {
    const locationData = uni.getStorageSync("location");
    if (locationData) {
      try {
        const parsedLocation = JSON.parse(locationData);
        if (parsedLocation && parsedLocation.city_name) {
          state.city = parsedLocation;
        } else {
          throw new Error("Invalid location data");
        }
      } catch {
        state.city = { ...DEFAULT_LOCATION };
        uni.setStorageSync("location", JSON.stringify(DEFAULT_LOCATION));
      }
    } else {
      state.city = { ...DEFAULT_LOCATION };
      uni.setStorageSync("location", JSON.stringify(DEFAULT_LOCATION));
    }
  } catch (error) {
    console.error("位置数据处理错误:", error);
    state.city = { ...DEFAULT_LOCATION };
    uni.setStorageSync("location", JSON.stringify(DEFAULT_LOCATION));
  }

  getData();
  const instance = getCurrentInstance().proxy;
  eventChannel = instance.getOpenerEventChannel();
});

const input = () => {
  if (state.keyword.length === 0) {
    state.is_search = true;
    getData();
  }
};

const cancel = () => {
  state.keyword = "";
  state.is_search = true;
  getData();
};

const search = () => {
  state.is_search = false;
  getData();
};

const getLocation = () => {
  state.city = {
    city_name: "定位中...",
    latitude: "",
    longitude: "",
  };

  uni.getLocation({
    type: "wgs84",
    success(res) {
      const { latitude, longitude } = res;
      getCityName(latitude, longitude);
    },
    fail(err) {
      console.error("定位失败:", err);
      // 定位失败时使用默认坐标
      getCityName(DEFAULT_LOCATION.latitude, DEFAULT_LOCATION.longitude);
      uni.showToast({
        title: "定位失败",
        icon: "none",
        duration: 2000,
      });
    },
  });
};

const getCityName = (latitude, longitude) => {
  sheep.$api.data
    .getcity({
      latitude: latitude,
      longitude: longitude,
    })
    .then((res) => {
      if (res.error === 0) {
        follow(latitude, longitude, res);
      }
    });
};

const follow = (latitude, longitude, res) => {
  const location = {
    latitude: latitude,
    longitude: longitude,
    city_name: res.data.name || DEFAULT_LOCATION.city_name,
	pid: res.data.pid || DEFAULT_LOCATION.pid,
  };

  state.city = { ...location };
  uni.setStorageSync("location", JSON.stringify(location));

  eventChannel?.emit("acceptDataFromOpenedPage", {
    data: "data from test page",
  });
};

const change = (item) => {
  const newLocation = {
    city_name: item.name,
    latitude: DEFAULT_LOCATION.latitude, // 使用默认坐标
    longitude: DEFAULT_LOCATION.longitude,
	pid: DEFAULT_LOCATION.pid,
  };

  state.city = { ...newLocation };
  uni.setStorageSync("location", JSON.stringify(newLocation));

  eventChannel?.emit("acceptDataFromOpenedPage", {
    data: "data from test page",
  });

  uni.navigateBack();
};

const getData = async () => {
  let { error, data } = await sheep.$api.data.getCityList({
    keyword: state.keyword,
  });
  if (error === 0) {
    state.list = data;
  }
};

const toAnchor = (index) => {
  state.scrollIntoView = `item-${index}`;
};
</script>

<style scoped lang="scss">
view {
  box-sizing: border-box;
}

.content {
  background-color: #f7f7f7;

  .search {
    height: 120rpx;
    z-index: 999;

    .search-box {
      width: 610rpx;
      height: 64rpx;
      border-radius: 8rpx;
      background: #fafafa;
    }

    .right {
      font-size: 28rpx;
      color: #999999;
    }
  }

  .location {
    height: 168rpx;

    .title {
      color: #999999;
    }

    .address {
      image {
        width: 28rpx;
        height: 32rpx;
      }
    }

    .reload {
      color: #e96458;

      image {
        width: 38rpx;
        height: 38rpx;
      }
    }
  }

  .scroll {
    height: calc(100vh - 304rpx);
    width: 100%;
    box-sizing: border-box;

    .title {
      font-family: Source Han Sans;
      font-size: 32rpx;
      font-weight: 700;
      color: #666666;
    }

    .list {
      .item {
        width: 200rpx;
        height: 68rpx;
        border-radius: 34rpx;
        background: #fafafa;
        line-height: 68rpx;
        font-family: Source Han Sans;
        font-size: 26rpx;
        color: #333333;
      }
    }
  }

  .fixed-index {
    position: fixed;
    right: 18rpx;
    top: 340rpx;
    font-family: PingFangSC;
    font-size: 24rpx;
    color: #999999;
  }
}
</style>
